/*
 * Copyright (c) 2006, 2023, webrx.cn All rights reserved.
 *
 */
package cn.webrx.servlet;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p></p>
 * <p>Powered by webrx On 2023-04-05 17:28:35</p>
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@WebServlet("/dbs.action")
public class Dbs extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();

        List<String> dbs = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try (
                Connection conn = DriverManager.getConnection("jdbc:mysql:/", "root", "root");
                PreparedStatement pst = conn.prepareStatement("show databases");
                ResultSet rs = pst.executeQuery()
        ) {
            while (rs.next()) {
                //dbs.add(String.format("\"%s\"", rs.getString(1)));
                dbs.add(rs.getString(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //String str = dbs.stream().collect(Collectors.joining(","));
        //out.print(String.format("[%s]", str));

        //out.print(JSONObject.toJSON(dbs));

        User user = new User();
        user.setId(100);
        user.setName("李四");
        user.setStu(false);
        user.setBirth(LocalDate.now());

        out.print(JSONObject.toJSON(user));

        out.flush();
        out.close();
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class User {
        private int id;
        private String name;
        private boolean stu;
        private LocalDate birth;
    }
}
